package com.longe.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 单元格列宽度自适应
 */
public class AutoSizeColumnDemo {

    public static void main(String[] args) throws Exception {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("firstSheet");

        createData(sheet, 0);
        createData(sheet, 1);

        /**这里设置自适应列宽，createData方法里面我们只定义了3列**/
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(2);

        FileOutputStream fos = new FileOutputStream(new File("D:\\TEST_POI\\autoSizeColumn.xlsx"));
        workbook.write(fos);
        fos.close();
        workbook.close();
    }

    private static void createData(Sheet sheet, int rowNum) {
        Row row = sheet.createRow(rowNum);//第一行
        Cell cell = row.createCell(0);
        if(rowNum == 0){
            cell.setCellValue("this is a string");//设置string类型的
        }else {
            cell.setCellValue("this is a more length string");//设置string类型的
        }

        cell = row.createCell(1);
        if(rowNum == 0){
            cell.setCellValue(3.14);//设置double类型的
        }else {
            cell.setCellValue(3.1415926);//设置double类型的
        }

        cell = row.createCell(2);
        cell.setCellValue(false);//设置boolean类型的
    }
}
